// pages/paired_detail/paired_detail.js
const getToken = require('../../utils/get_token.js');
let [md, openId, goodId, tuanId, pageNo]=['','','','',1];
const ckToken = async (that) => {//token确认
  let nTime = Math.floor(new Date().getTime() / 1000);
  let oldTime = wx.getStorageSync('ntime') || 0;
  if (nTime < oldTime)//现在的时间小于到期时间
  {
    thou(that);
  } else {
    await getToken.getToken();
    thou(that);
  }
}
const thou = (that) => {//token没有失效时执行的代码
  getA(that);
  likeList(that);
}
const forMore = function (that, data, t) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].match(/hexishop/g)) {
      data[i] = '/upload/head/default.png';
    }
    if (i < t) {
      that.data.aList.push({ 'img': data[i], 'show': true })
    } else {
      that.data.aList.push({ 'img': data[i], 'show': false })
    }
  }
  that.setData({
    aList: that.data.aList
  })
}
const likeList = (that) => {//猜你喜欢
  that.setData({
    hidden: false
  })
  let params = ['shop/pingTuan/guessYouLike', {"openId":openId,"memberId": md ,"pageSize":pageNo,"seeType":2,"pinTuanGoodsId": goodId,"orderSn":""}]
  getToken.getData(function (res) {
    console.log(res.data)
    let data = res.data;
    if (data.rows.length > 0) {
      for (let i = 0; i < data.rows.length; i++) {
       // data.rows[i].goodsImageStore = data.rows[i].goodsImageStore.substring(1, data.rows[i].goodsImageStore.length - 1);
        data.rows[i].goodsImageStore = JSON.parse(data.rows[i].goodsImageStore);
        data.rows[i].img = 'http://www.globalhexi.com/' + data.rows[i].goodsImageStore[0].path + '/small/' + data.rows[i].goodsImageStore[0].id + '.jpg';
        data.rows[i].intPinPrice = (data.rows[i].intPinPrice / 100).toFixed(2);
        data.rows[i].intPrice = (data.rows[i].intPrice / 100).toFixed(2);
        that.data.lkList.push(data.rows[i]);
      }
    }
    that.setData({
      lkList: that.data.lkList,
      hidden: true
    })
  }, ...params)
};
const getA = (that) => {//获取团列表
  let params = ['shop/pingTuan/gtmll', {"tuanId": tuanId,"logo":false}]
  getToken.getData(function (res) {
    console.log(res.data)
    let datas = res.data;
    if (that.data.types=='2'){//参团
      if(datas.lastNum>0){
        that.data.haShow=true;
      }else{
        that.data.comShow=true;
      }
    }
    let creatime = datas.endTime;
    datas.needPayPay = datas.needPayPay / 100;
    let all = 0, aOll = [],aNum=0;
    all=datas.rows.reduce(function(pre,cur){return cur.buyCount+pre },0)//获取总人数
    for (let i = 0; i < datas.rows.length; i++) {
      if (datas.rows[i].logo.indexOf('http') == -1) {
          datas.rows[i].logo = 'http://www.globalhexi.com/' + datas.rows[i].logo;
      }
      if (datas.rows[i].logo.match(/hexishop/g)) {
        datas.rows[i].logo= '/upload/head/default.png';
      }
      for (let j = 0; j < datas.rows[i].buyCount; j++) {
        aOll.push(datas.rows[i].logo);
        aNum++;
        if(aNum>=100){
          break;
        }
      }
    }
    that.data.aList=aOll;
    datas.tuanMemberNums = all + datas.lastNum;       	        		
    let ktId = datas.tuanSetId;
    datas.address = JSON.parse(datas.address);
    datas.cityName = datas.address.areaStore + datas.address.address;
    that.data.ztShow=datas.isGroupBuy?true:false;
    if (datas.state == 0)//还能参团
    {
      let getTime = new Date().getTime();
      var sTime = (creatime - getTime) / 1000;
      fresh(that, sTime);
      that.data.inset=setInterval(function () {
         sTime--;
        fresh(that, sTime)
     }, 1000)
    } else {//拼团已满
      that.data.yShow = false;
      that.data.mShow = true;
    }
    that.data.re = datas;
    that.setData({
      re: that.data.re,
      aList: that.data.aList,
      haShow:that.data.haShow,
      comShow:that.data.comShow,
      ztShow: that.data.ztShow,
      yShow: that.data.yShow,
      mShow: that.data.mShow,
      tuanMemberNums:datas.tuanMemberNums
    })
  }, ...params)
};
const getDeati = (that) => {//获取详情
  wx.request({
    header: { 'content-type': 'application/x-www-form-urlencoded' },
    method: 'POST',
    url: 'https://interface.globalhexi.cn/shop/pingTuan/getPinTuanNewDetail',
    data: { id: goodId },
    success: function (res) {
      console.log(res.data)
      let goods = res.data.result;
      let Urls = JSON.parse(goods.goodsPinTuanVo.img);
      goods.imgSrc = `https://www.globalhexi.com/${Urls[0].path}/small/${Urls[0].id}.jpg`;
      that.data.gname=goods.goodsPinTuanVo.goodsName;
      that.setData({
        simg: goods.imgSrc,
        gname:that.data.gname
      })
    }
  })
};
var adzo=function(num) {
	if (num < 10)
		return ('0' + num);
	else
		return num;
}
var fresh=function(that,data){
  let h,m,s;
	if (data <= 0) {
    that.data.sShow=true;
    that.data.yShow=false;
	} else {
    h = adzo(parseInt(data / 3600));
    m = adzo(parseInt((data / 60) % 60));
    s = adzo(parseInt(data % 60));
		that.data.times = h + ':' + m + ':' + s;
  }
  that.setData({
    sShow:that.data.sShow,
    yShow:that.data.yShow,
    house:h,
    minutes:m,
    seconds:s,
    times:that.data.times
  })
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nopShow: true,
    more: true,
    boolT: true,
    boxShow: true,
    nShow:false,
    ztShow:false,
    sShow:false,
    yShow:true,
    mShow:false,
    haShow:false,
    comShow:false,
    house:'00',
    minutes:'00',
    seconds:'00',
    message:"",
    gname:'',
    simg:'',
    tuanMemberNums:0,
    aList: [],
    dList: [],
    lkList:[],
    types:'1',
    inset:null,
    times:'',
    info:'恭喜,开团成功',
    hidden: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    pageNo=1;
    let incom = Number(options.incom);
    goodId = options.id;
    tuanId = options.tuanid;
    that.data.types = options.types;
    console.log(that.data.types)
    if (that.data.types=='2')
    {
      that.setData({info:'恭喜,参团成功'})
    }else{
      if (incom>0)
      {
        that.data.message = '*通知：拼团成功，可获得福利金￥' + incom;
        that.setData({
          nShow:true,
          message: that.data.message
        })
      }
    }
    openId = wx.getStorageSync('openId') || '';
    md = wx.getStorageSync('memberId') || '';
    wx.setStorageSync('hebiRedFlag', '234');
    getDeati(that);
    ckToken(that);
  },
  onShow: function () {

  },
/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {
  let that = this;
  clearInterval(that.data.inset);
},
goDe:function(e){//商品详情
  let that = this;
  if (that.data.boolT) {
    that.data.boolT = false;
    wx.navigateTo({
      url: '../paired_detail/paired_detail?scene=' + goodId,
      success: function () {
        setTimeout(function () { that.data.boolT = true;}, 500)
      }
    })
  }
},
ha_colse:function(){
  let that = this;
  that.setData({
    haShow:false
  })
},
com_colse:function(){
  let that = this;
  that.setData({
    comShow:false
  })
},
go_center:function(){
  let that = this;
  if (that.data.boolT) {
    that.data.boolT = false;
    wx.switchTab({
      url: '../personal/personal',
      success: function () {
        setTimeout(function () { that.data.boolT = true;}, 500)
      }
    })
  }
},
enter: function (e) {
  let that = this;
  if (that.data.boolT) {
    that.data.boolT = false;
    wx.navigateTo({
      url: '../paired_detail/paired_detail?scene=' + e.currentTarget.dataset.id,
      success: function () {
        setTimeout(function () {
          that.data.boolT = true;
        }, 500)
      }
    })
  }
},
goIndex: function (e) {//参团
  let that = this;
  if (that.data.boolT) {
    that.data.boolT = false;
    wx.reLaunch({
      url: '../index/index',
      success: function () {
        setTimeout(function () {
          that.data.boolT = true;
        }, 500)
      }
    })
  
  }
},
  /**
 * 页面上拉触底事件的处理函数
 */
  onReachBottom: function () {
    let that = this;
    pageNo++;
    likeList(that);

  }, 
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let that=this;
    let tit='【仅剩' + that.data.re.lastNum + '个】我' + that.data.re.needPayPay + '元拼了' + that.data.gname;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res)
    }
    return {
      title: tit,
      imageUrl: that.data.simg,
      path: '/pages/tuxedo/tuxedo?id=' + goodId + '&tuanid=' + tuanId,
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  }
})